package com.fuyun.rpc.client.proxy.retrystrategy;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: zrq1351
 * @date: 2025/2/15
 */
@Slf4j
public class RetryStrategyFactory {

	private static final Map<String, RetryStrategy> INSTANCE_CACHE = new ConcurrentHashMap<>();

	/**
	 * 获取指定类名的 RetryStrategy 单例实例
	 *
	 * @param className 实现类全限定名
	 * @return RetryStrategy 单例对象
	 */
	public static RetryStrategy getInstance(String className) {
		return INSTANCE_CACHE.computeIfAbsent(className, key -> {
			log.info("获取重试策略：{}", className);
			try {
				Class<?> clazz = Class.forName(key);
				if (!RetryStrategy.class.isAssignableFrom(clazz)) {
					throw new IllegalArgumentException("Class " + key + " 未实现 RetryStrategy 接口");
				}
				return (RetryStrategy)clazz.getDeclaredConstructor().newInstance();
			} catch (ClassNotFoundException e) {
				throw new RuntimeException("找不到类: " + key, e);
			} catch (InstantiationException e) {
				throw new RuntimeException("无法实例化类: " + key + "（可能是抽象类）", e);
			} catch (IllegalAccessException e) {
				throw new RuntimeException("无权限访问构造函数: " + key, e);
			} catch (NoSuchMethodException e) {
				throw new RuntimeException("类 " + key + " 缺少无参构造函数", e);
			} catch (InvocationTargetException e) {
				throw new RuntimeException("构造函数执行失败: " + key, e.getTargetException());
			}
		});
	}

}